<?php

namespace App\Trip\Notify\Sms;

use Exception;
use Overtrue\EasySms\EasySms;
use Overtrue\EasySms\Exceptions\InvalidArgumentException;
use Overtrue\EasySms\Exceptions\NoGatewayAvailableException;
use Overtrue\EasySms\Strategies\OrderStrategy;

class Sms
{
    private EasySms $instance;
    private array   $gateways = [];
    private string  $mobile;
    private         $message;

    public function __construct()
    {
        $config         = [
            // HTTP 请求的超时时间（秒）
            'timeout'  => 5.0,
            // 默认发送配置
            'default'  => [
                // 网关调用策略，默认：顺序调用
                'strategy' => OrderStrategy::class,
                // 默认可用的发送网关
                'gateways' => [
                    'qcloud',
                ],
            ],
            // 可用的网关配置
            'gateways' => [
                'qcloud' => config('qcloud.sms'),
            ],
        ];
        $this->instance = new EasySms($config);
    }

    public function setGateways(array $gateways): static
    {
        $this->gateways = $gateways;
        return $this;
    }

    public function setMobile(string $mobile): static
    {
        $this->mobile = $mobile;
        return $this;
    }

    public function setMessage($message): static
    {
        $this->message = $message;
        return $this;
    }

    /**
     * @throws NoGatewayAvailableException
     * @throws InvalidArgumentException
     * @throws Exception
     */
    public function send(string $mobile, $message): array
    {
        if (!$mobile && !$this->mobile) {
            throw new Exception("请填写手机号");
        }

        if (!$mobile) {
            $mobile = $this->mobile;
        }

        if (!$message) {
            $message = $this->message;
        }

        return $this->instance->send($mobile, $message, $this->gateways);
    }
}